package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.EnInfo;
import cn.com.hhrcw.entity.OpShielding;
import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.mapstruct.EnInfoConvert;
import cn.com.hhrcw.params.EnInfoParams;
import cn.com.hhrcw.service.IEnInfoService;
import cn.com.hhrcw.service.IOpShieldingService;
import cn.com.hhrcw.service.ISysUserService;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.ConfirmInfoVO;
import cn.com.hhrcw.vo.EnInfoVO;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.function.Function;

/**
 * 公司信息
 *
 * @author jiangdong
 * @since 2020-10-29
 */
@RestController
@Slf4j
@RequestMapping("/personal/enInfo")
@Api(tags = "公司信息表")
@Validated
public class EnInfoController extends JeecgController<EnInfo, IEnInfoService> {

    @Autowired
    private IEnInfoService ennfoService;

    @Autowired
    private EnInfoConvert enInfoConvert;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private IOpShieldingService opShieldingService;

    /**
     * 通过用户id查询用户信息以及公司信息
     *
     * @param id 用户id
     * @return
     */
    @GetMapping("/confirm/info")
    public Result<ConfirmInfoVO> confirmInfo(String id) {
        SysUser user = userService.getById(id);

        try {
            String departId = jdbcTemplate.queryForObject("select dep_id sys_user_depart where user_id = ?", new Object[]{id}, String.class);
            EnInfo info = service.getById(departId);
            return Result.ok(new ConfirmInfoVO(user, info));
        } catch (Exception e) {
            for (StackTraceElement elements : e.getStackTrace()) {
                log.error(elements.toString());
            }
            return Result.ok(new ConfirmInfoVO());
        }
    }

    /**
     * 分页列表查询
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog("公司信息表-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<EnInfoVO>> list(EnInfoParams params, HttpServletRequest request) {
        QueryWrapper<EnInfo> queryWrapper = QueryGenerator.initQueryWrapper(enInfoConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<EnInfo> page = ennfoService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<EnInfo, EnInfoVO> fun = enInfo -> enInfoConvert.toVO(enInfo);

        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 企业信息根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    public Result<?> queryById(String id) {
        EnInfo enInfo = ennfoService
                .lambdaQuery()
                .eq(EnInfo::getId, id)
                .eq(EnInfo::getDelFlag, false)
                .one();
        if (enInfo == null) {
            return Result.error(404, "数据不存在");
        }
        EnInfoVO enInfoVO = enInfoConvert.toVO(enInfo);
        String personnel = enInfoVO.getEnPersonnel();
        if (StrUtil.isNotBlank(personnel)) {
            boolean equals = "10000-99999999".equals(personnel);
            if (equals) {
                enInfoVO.setEnPersonnel("10000以上");
            }
        }
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        if (sysUser != null) {
            int count = opShieldingService.lambdaQuery().eq(OpShielding::getComId, enInfo.getId())
                    .eq(OpShielding::getDelFlag, false).eq(OpShielding::getUserId, sysUser.getId()).count();
            enInfoVO.setShFlag(count > 0);
        }
        return Result.ok(enInfoVO);
    }

    /**
     * 添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("公司信息表-添加")
    @ApiOperation(value = "添加", notes = "添加")
    @RequiresPermissions("enInfo:add")
    public Result<?> add(@RequestBody @Valid EnInfoParams params) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        EnInfo enInfo = enInfoConvert.toEntity(params);
        enInfo.setCreateBy(sysUser.getId());
        enInfo.setCreateTime(DateUtil.date());
        enInfo.setDelFlag(false);

        boolean saved = ennfoService.save(enInfo);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog("公司信息表-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("enInfo:edit")
    public Result<?> edit(@RequestBody @Valid EnInfoParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        EnInfo enInfo = enInfoConvert.toEntity(params);
        enInfo.setUpdateBy(sysUser.getId());
        enInfo.setUpdateTime(DateUtil.date());

        boolean updated = ennfoService.updateById(enInfo);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog("公司信息表-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("enInfo:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<EnInfo> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(EnInfo::getId, id)
                .set(EnInfo::getDelFlag, true)
                .set(EnInfo::getUpdateBy, sysUser.getUsername())
                .set(EnInfo::getUpdateTime, DateUtil.date());

        boolean deleted = ennfoService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, EnInfoParams params) {
        EnInfo enInfo = enInfoConvert.toEntity(params);
        enInfo.setDelFlag(false);
        QueryWrapper<EnInfo> queryWrapper = QueryGenerator.initQueryWrapper(enInfo, request.getParameterMap());
        List<EnInfo> data = ennfoService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("公司信息表", "公司信息表");
        String url = super.exportXls(exportParams, EnInfoVO.class, enInfoConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, EnInfo.class);
    }

}
